//
//  TCLYInformationViewController.m
//  YuErmuYing
//
//  Created by LYang on 16/8/24.
//  Copyright © 2016年 Tiancheng. All rights reserved.
//

#import "TCLYInformationViewController.h"
#import "TCLYMineModel.h"
#import "TCLYCommunityModel.h"
#import "Masonry.h"
#import "Macros.h"
#import "UIImageView+WebCache.h"
#import "TCLYUser.h"
#import "TCLYRegisterView.h"

@interface TCLYInformationViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewConstraintHeight;
@property (weak, nonatomic) IBOutlet UIButton *sexBtn;
@property (weak, nonatomic) IBOutlet UIButton *manBtn;
@property (nonatomic, strong)TCLYMineModel * mineModel;
@property (nonatomic, strong)TCLYCommunityModel * uploadImageModel;
@property (weak, nonatomic) IBOutlet UITextField *nickNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *QQTextField;
@property (weak, nonatomic) IBOutlet UITextField *emailTxetField;
@property (weak, nonatomic) IBOutlet UIButton *headerBtn;
@property (nonatomic, strong) NSMutableArray * imageArr;
@property (nonatomic, strong) TCLYUser * user;
@property (nonatomic, strong) TCLYRegisterView * promView;
@end

@implementation TCLYInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createTitleView];
    //添加触碰手势(为了可以隐藏键盘)
    UITapGestureRecognizer * textFeildTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:textFeildTap];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadInformation) name:@"loadInformation" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateInformationSucceed) name:@"updateInformationSucceed" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateInformationSucceed) name:@"updateInfor" object:nil];
    
    self.promView = [[TCLYRegisterView alloc] init];
    self.uploadImageModel = [[TCLYCommunityModel alloc] init];
    self.mineModel = [[TCLYMineModel alloc] init];
    self.user = [[TCLYUser alloc] init];
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId, @"uid", nil];
    [self.mineModel loadInformationParameter:dic];
    self.bgView.backgroundColor = bgColor;
    self.view.backgroundColor = bgColor;
    
    self.imageArr = [NSMutableArray array];
    [self createBtn];
}
-(void)createTitleView{
    self.navigationController.navigationBar.barStyle = UIBarMetricsCompactPrompt;
    self.navigationController.navigationBar.backgroundColor = statusColor;
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, screenWidth, 20)];
    view.backgroundColor = navColor;
    [self.navigationController.navigationBar addSubview:view];
    
    UILabel * titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"资料";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.frame = CGRectMake(0, 0, 50, 20);
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.navigationItem.titleView = titleLabel;
    
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(12, 22, 20, 20);
    [leftBtn setImage:[UIImage imageNamed:@"left"] forState:UIControlStateNormal];
    leftBtn.tag = 91;
    [leftBtn addTarget:self action:@selector(statusBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
}
-(void)statusBtnAction:(id)sender{
    switch (((UIButton *)sender).tag) {
        case 91:{
            [self.navigationController popViewControllerAnimated:YES];
            self.navigationController.navigationBarHidden = NO;
            self.tabBarController.tabBar.hidden = YES;
        }
            break;
        case 92:{
            
        }
            break;
    }
}

-(void)loadInformation{
    self.nickNameTextField.text = self.mineModel.informationDic[@"name"];
    if (![self.mineModel.informationDic[@"sex"] isEqual:@0]) {
        self.sexBtn.selected = NO;
        self.manBtn.selected = YES;
    }else{
        self.sexBtn.selected = YES;
        self.manBtn.selected = NO;
    }
    self.QQTextField.text = self.mineModel.informationDic[@"qq"];
    self.emailTxetField.text = self.mineModel.informationDic[@"email"];
    NSURL * url = [NSURL URLWithString:self.mineModel.informationDic[@"pic"]];
    UIImageView * imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"LYJia2"]];
    [self.headerBtn setImage:imageView.image forState:UIControlStateNormal];
}
-(void)createBtn{
    UIButton * saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    saveBtn.backgroundColor = btnColor;
    saveBtn.layer.cornerRadius = 5;
    saveBtn.layer.masksToBounds = YES;
    [saveBtn addTarget:self action:@selector(saveBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBtn];
    
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.right.mas_equalTo(-12);
        make.height.mas_equalTo(46);
        make.bottom.mas_equalTo(-50);
    }];
    
    [self.manBtn setImage:[UIImage imageNamed:@"mineTic"] forState:UIControlStateNormal];
    [self.manBtn setImage:[UIImage imageNamed:@"mineTick-click"] forState:UIControlStateSelected];
    self.manBtn.selected = YES;
    
    [self.sexBtn setImage:[UIImage imageNamed:@"mineTic"] forState:UIControlStateNormal];
    [self.sexBtn setImage:[UIImage imageNamed:@"mineTick-click"] forState:UIControlStateSelected];
    self.sexBtn.selected = NO;
    
    [self.headerBtn addTarget:self action:@selector(updateHeaderImageView) forControlEvents:UIControlEventTouchUpInside];
    [self.headerBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(IBAction)sexBtnAction:(id)sender{
    switch (((UIButton *) sender).tag) {
        case 401:{
            self.manBtn.selected = YES;
            self.sexBtn.selected = NO;
        }
            break;
        case 402:{
            self.manBtn.selected = NO;
            self.sexBtn.selected = YES;
        }
            break;
    }
}
//隐藏键盘的方法
-(void)dismissKeyboard{
    for (int j = 0; j<3; j++) {
        UITextField * textField = [self.view viewWithTag:501+j];
        [textField resignFirstResponder];
    }
}
-(void)saveBtnAction{
    int sex = 0;
    if (self.sexBtn.selected == YES) {
        sex = 1;
    }
    
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId,@"uid",self.nickNameTextField.text,@"name", [NSString stringWithFormat:@"%d",sex], @"sex", self.QQTextField.text, @"qq", self.emailTxetField.text, @"email", nil];
    NSLog(@"这里是上传资料%@",dic);
    NSLog(@"%ld",self.imageArr.count);
    if (self.imageArr.count != 0) {
        //上传头像
        [self updataPhotoFor:self.imageArr Parameter:dic];
    }else{
        [self.mineModel updateInformationParameter:dic];
    }
}

//上传图片
-(void)updataPhotoFor:(NSArray *) image Parameter:(NSDictionary * )parameter{
    NSLog(@"%@",image);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@openid_head.png", str];
    self.uploadImageModel.isInformation = YES;
    [self.uploadImageModel uploadImageArray:image Parameter:parameter ParamName:@"image" FileName:fileName MimeType:@"image/png" UrlStr:@"http://112.74.114.1/Parenting/index.php/api/user/editinfo"];
    
}
-(void)updateInformationSucceed{
    if ([self.uploadImageModel.updateInformationStr isEqual:@200]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loadingMineHome" object:self];
        self.navigationController.navigationBarHidden = YES;
        self.tabBarController.tabBar.hidden = NO;
        [self.navigationController popToRootViewControllerAnimated:YES];
        return;
    }
    if ([self.mineModel.updateInforStr isEqual:@200]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loadingMineHome" object:self];
        self.navigationController.navigationBarHidden = YES;
        self.tabBarController.tabBar.hidden = NO;
        [self.navigationController popToRootViewControllerAnimated:YES];
        return;
    }
    [self.promView prompt:@"修改失败" Controller:self];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

-(void)updateHeaderImageView{
    UIAlertController * alertCtr = [UIAlertController alertControllerWithTitle:@"选择头像" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * takePictureAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self snapImage];
        NSLog(@"拍照");
    }];
    UIAlertAction * albumAction = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self localPhoto];
        NSLog(@"从相册选取");
    }];
    UIAlertAction * backAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    [alertCtr addAction:takePictureAction];
    [alertCtr addAction:albumAction];
    [alertCtr addAction:backAction];
    
    [self presentViewController:alertCtr animated:YES completion:nil];
}
//*****************************拍照**********************************
- (void) snapImage
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        __block UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
        ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
        ipc.delegate = self;
        ipc.allowsEditing = YES;
        ipc.navigationBar.barTintColor =[UIColor whiteColor];
        ipc.navigationBar.tintColor = [UIColor whiteColor];
        ipc.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
        [self presentViewController:ipc animated:YES completion:^{
            ipc = nil;
        }];
    } else {
        NSLog(@"模拟器无法打开照相机");
    }
}
//从相册选取图片
#define CommonThimeColor HEXCOLOR(0x11a0ee)
-(void)localPhoto
{
    __block UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    picker.navigationBar.barTintColor =[UIColor whiteColor];
    picker.navigationBar.tintColor = [UIColor blackColor];
    picker.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};
    [self presentViewController:picker animated:YES completion:^{
        picker = nil;
    }];
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //完成选择
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //NSLog(@"type:%@",type);
    if ([type isEqualToString:@"public.image"]) {
        //转换成NSData
        UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/headerImage.png"] contents:data attributes:nil];
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:^{
            
            //设置头像
            [self.headerBtn setImage:image forState:UIControlStateNormal];
            [self.imageArr addObject:image];
        }];
        
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
